// ctrl_multi_login.go
package controllers

import (
	"bsm/logger"
	"bsm/services"
	"net/http"

	"github.com/gin-gonic/gin"
)

type MultiLoginController interface {
	GetSessions(ctx *gin.Context)
	TerminateSession(ctx *gin.Context)
	TerminateOtherSessions(ctx *gin.Context)
}

type multiLoginControllerImpl struct {
	sessionService services.RedisSessionService
}

// NewMultiLoginController 创建多点登录控制器
func NewMultiLoginController(sessionService services.RedisSessionService) MultiLoginController {
	return &multiLoginControllerImpl{
		sessionService: sessionService,
	}
}

func (c *multiLoginControllerImpl) GetSessions(ctx *gin.Context) {
	userID, exists := ctx.Get("user_id")
	if !exists {
		ctx.JSON(http.StatusBadRequest, gin.H{"信息": "用户账号获取失败"})
		return
	}
	sessions, err := c.sessionService.GetUserSessions(userID.(string))

	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "MultiLogin-GetSessions",
		}).Errorf("获取会话列表失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "获取会话列表失败"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":     0,
		"sessions": sessions,
		"count":    len(sessions),
	})
}

func (c *multiLoginControllerImpl) TerminateSession(ctx *gin.Context) {
	var request struct {
		SessionID string `json:"session_id" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&request); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"信息": "参数错误"})
		return
	}

	err := c.sessionService.RemoveSession(request.SessionID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "MultiLogin-TerminateSession",
		}).Errorf("终止会话失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "终止会话失败"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "会话已终止",
	})
}

func (c *multiLoginControllerImpl) TerminateOtherSessions(ctx *gin.Context) {
	userID := ctx.GetInt("user_id")
	currentSessionID := ctx.GetHeader("X-Session-ID")

	// 如果请求头中没有session ID，尝试从Authorization token中提取
	if currentSessionID == "" {
		authHeader := ctx.GetHeader("Authorization")
		if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
			// 这里可以添加从token解析session ID的逻辑
			// 简单起见，我们返回错误
			ctx.JSON(http.StatusBadRequest, gin.H{"信息": "无法确定当前会话"})
			return
		}
	}

	terminatedCount, err := c.sessionService.TerminateOtherSessions(userID, currentSessionID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "MultiLogin-TerminateOtherSessions",
		}).Errorf("终止其他会话失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "终止其他会话失败"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":             0,
		"msg":              "其他会话已终止",
		"terminated_count": terminatedCount,
	})
}
